import net from 'net'

export class SocketClient {
    private client = new net.Socket();

    private callBack: Function;

    constructor() {
        // let rl = readline.createInterface({
        //     // 调用std接口
        //     input: process.stdin,
        //     output: process.stdout
        // })
        this.client.on('connect', () => {
            console.log('Sockert-连接成功!!')
        })
        this.client.setEncoding('binary');


        this.client.on('data', this.onMsg.bind(this));
        this.client.on('error', (e) => {
            console.log(e.message);
        })
    }

    connect() {
        console.log('中转模拟牵手客户端');

        this.client.destroy();
        this.client.connect(9099, '47.99.149.78');
    }

    private onMsg(buf: Buffer) {
        // console.log('Sockert-收到消息：', chunk);

        // var ab = new ArrayBuffer(buf.length);
        // var view = new Uint8Array(ab);
        // for (var i = 0; i < buf.length; ++i) {
        //     view[i] = buf[i];
        // }
        // console.dir(typeof buf);
        this.callBack && this.callBack(buf);
    }

    setReceiveCallBack(func: (data) => void) {
        this.callBack = func;
    }

    onSend(mes: ArrayBuffer) {
        // console.log('Sockert-发送消息：', mes)
        let uint8Array = new Uint8Array(mes)
        this.client.write(uint8Array);
    }
}